/*
 * @Author: new-wang
 * @Date: 2025-08-29 10:57:58
 * @LastEditors: new-wang
 * @LastEditTime: 2025-08-29 15:53:35
 * @FilePath: \nest-demo\src\common\decorators\clientInfo.decorator.ts
 * @Description: clientInfo 装饰器
 */
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
// Useragent 是一个高性能的用户代理字符串解析器
import * as Useragent from 'useragent'
import { GetNowDate } from 'src/common/utils'

export const ClientInfo = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest()
    // 获取真实User-Agent：优先从X-Original-User-Agent头获取
    const userAgentHeader =
      request.headers['x-original-user-agent'] || request.headers['user-agent']
    const agent = Useragent.parse(userAgentHeader)
    const os = agent.os.toJSON().family
    const browser = agent.toAgent()
    // 获取真实IP：优先从X-Forwarded-For头获取
    let ip = request.ip
    if (request.headers['x-forwarded-for']) {
      const ips = request.headers['x-forwarded-for'].split(',')
      ip = ips[0].trim()
    }
    const clientInfo = {
      userAgent: userAgentHeader,
      ipaddr: ip,
      browser: browser,
      os: os,
      loginLocation: '',
      dateTime: GetNowDate(),
      userName: request.user?.user?.userName,
    }
    return clientInfo
  },
)

export type ClientInfoDto = {
  userAgent: string
  ipaddr: string
  browser: string
  os: string
  loginLocation: string
  dateTime: string
  userName?: string
}
